﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Electure.DAL;

namespace Electure.Admin
{
    public partial class NewsItems : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (IsPostBack) return;

            using (var rep = RepositoryFactory.GetNewsRepository())
            {
                repNews.DataSource = rep.GetAll();
                repNews.DataBind();
            }

        }

        protected void repNews_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
            {
                var newsItem = (News)e.Item.DataItem;
                
                Label lbName = (Label)e.Item.FindControl("lbName");

                Button btEdit = (Button)e.Item.FindControl("btEdit"),
                    btDelete = (Button)e.Item.FindControl("btDelete");

                btEdit.CommandArgument = btDelete.CommandArgument = newsItem.ID.ToString();
                lbName.Text = newsItem.Name;
            }
        }

        protected void repNews_ItemCommand(object source, RepeaterCommandEventArgs e)
        {

            if (e.CommandName == "Edit")
            {
                Response.Redirect(string.Format("EditNews.aspx?id={0}", e.CommandArgument));
            }
            else if (e.CommandName == "Delete")
            {
                using (var rep = RepositoryFactory.GetNewsRepository())
                {
                    rep.Delete(int.Parse(e.CommandArgument.ToString()));
                }
                Response.Redirect("NewsList.aspx");
            }
        }
    }
}